<?php
/**
 * Eren Framework
 * 
 * Timer
 * 
 * @category System
 * @author Manu Soros Leu
 * @copyright manusoros@gmail.com
 */

class Eren_Timer
{
    /**
     * Log the default begin time
     * 
     * @var float
     */
    static private $_timeStart = NULL;
    
    /**
     * Log the key begin time 
     * @var array
     */
    static private $_timeStartArray = array();
    
    /**
     * Log the default used time
     * 
     * @var float
     */
    static private $_timeUsed  = NULL;
    
    /**
     * Log the key used time 
     * @var array
     */
    static private $_timeUsedArray = array();
    
    /**
     * Format out time
     * 
     * @param float beign
     * @param float end
     * 
     * @return float
     */
    static private function _formate($beign, $end)
    {
        return number_format(($end-$beign)*1000, 3);
    }
    
    /**
     * Begin Timer
     * 
     * @param string $key
     */
    static public function start($key = NULL)
    {
        if($key!=NULL && !is_string($key)){
            throw new Eren_Exception("The first param of start must be String.");
        }
        
        list($usec,$sec) = explode(" ",microtime());
        if($key == NULL){
            self::$_timeStart = (float)$usec + (float)$sec;
        }else{
            self::$_timeStartArray[$key] = (float)$usec + (float)$sec;
        }
    }
    
    /**
     * End Timer and return Used time
     * 
     * @param string $key
     * 
     * @return float
     */
    static public function end($key = NULL)
    {
        if($key!=NULL && !is_string($key)){
            throw new Eren_Exception("The first param of end must be String.");
        }
        
        list($usec,$sec) = explode(" ",microtime());
        $now = (float)$usec + (float)$sec;
        if($key == NULL){
            self::$_timeUsed = self::_formate(self::$_timeStart, $now);
        }else if(isset(self::$_timeStartArray[$key])){
            self::$_timeUsedArray[$key] = self::_formate(self::$_timeStartArray[$key], $now);
        }else{
            self::$_timeUsedArray[$key] = 0;
        }

        return $key==NULL ? self::$_timeUsed : self::$_timeUsedArray[$key];
    }
    
    /**
     * Get the key used time
     * 
     * @param string $key
     *
     * @return float
     */
    static public function used($key = NULL)
    {
        if($key!=NULL && !is_string($key)){
            throw new Eren_Exception("The first param of end must be String.");
        }
        
        if(isset(self::$_timeUsedArray[$key])){
            return self::$_timeUsedArray[$key];
        }else{
            return 0;
        }
    }
    
    /**
     * Get all used time
     * 
     * @return array
     */
    static public function all()
    {
        return self::$_timeUsedArray;
    }
}
